<template>
  <a-row :gutter="24">
    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-tree
          :treeData="treeList"
          v-if="treeList.length"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields"
        />
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="6" :sm="24">
                <a-form-item label="网关名称">
                  <a-select
                    :showSearch="true"
                    optionFilterProp="children"
                    style="width: 100%"
                    v-model="queryParam.gatewayId"
                    allow-clear
                    placeholder="请选择网关名称"
                  >
                    <a-select-option v-for="(item, ind) in gatewayList" :key="ind" :value="item.id">{{ item.gatewayName }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="(!advanced && 6) || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="padding-left: 16px;"
                  :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                >
                  <a-button
                    type="primary"
                    class="btn_search_reset"
                    @click="$refs.table.refresh()"><a-icon type="search" />查询</a-button>
                  <a-button
                    style="margin-left: 8px"
                    class="btn_search_reset"
                    @click="
                      () => {
                        queryParam = { deviceIds: deviceIds.toString() }
                        $refs.table.refresh()
                      }
                    "><a-icon type="reload" />重置</a-button
                  >
                </span>
              </a-col>
              <a-col :md="(!advanced && 12) || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  style="float: right;"
                  :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                >
                  <a-button type="primary" class="btn_add" @click="syncModel()">同步模型</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowKey="record => record.id"
        >
          <span slot="fileId" slot-scope="text, record">
            <a @click="$refs.playForm.play(record)">{{ text === null || text === '' ? '无' : '播放' }}</a>
          </span>
          <span slot="failureLevel" slot-scope="text">
            {{ failureLevelFilter(text) }}
          </span>
          <span slot="action" slot-scope="text, record">
            <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
              <a class="btn_del">删除</a>
            </a-popconfirm>
          </span>
        </s-table>

        <play-form ref="playForm" @ok="handleOk" />
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import { STable } from '@/components'
import { page, del, sync } from '@/api/modular/main/bizcollectionmodelmanage/collectionModelManage'
import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'
import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'
import playForm from './playForm'

export default {
  components: {
    STable,
    playForm
  },

  data () {
    return {
      data: [],
      page: {},
      loading: false,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {
        stationId: 0
      }, // 查询参数
      columns: [
        // 表头
        {
          title: '网关名称',
          dataIndex: 'gatewayName'
        },
        {
          title: '模型名称',
          dataIndex: 'faultName'
        },
        {
          title: '故障等级',
          dataIndex: 'failureLevel',
          scopedSlots: { customRender: 'failureLevel' },
          align: 'center'
        },
        // {
        //   title: '期望ID编号',
        //   dataIndex: 'expectAccessToken'
        // },
        // {
        //   title: '期望分组',
        //   dataIndex: 'expectGroupId'
        // },
        {
          title: '上报时间',
          dataIndex: 'createTime',
          align: 'center',
          width: 180
        },
        {
          title: '模型文件库',
          dataIndex: 'fileId',
          scopedSlots: { customRender: 'fileId' },
          width: 50,
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 50,
          align: 'center'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then(res => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id'
      },
      stationId: 0,
      treeList: [],
      treeLoading: true,
      gatewayList: [],
      deviceIds: [],
      stationTreeIndex: -1,
      failureLevelList: []
    }
  },
  created () {
    this.getStationTree()
    this.getFailureLevelList()
  },
  methods: {
    failureLevelFilter (record) {
        let str = ''
        this.failureLevelList.forEach(item => {
           if (record === item.code) {
            str = item.value
           }
        })
        return str
    },
    getFailureLevelList () {
        sysDictTypeDropDown({ code: 'fault_level' }).then((res) => {
          if (res.success) {
            this.failureLevelList = res.data
          }
        })
      },
    del (record) {
      del(record)
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handleClick (e) {
      if (e.length > 0) {
        this.queryParam = {}
        this.stationId = e.toString()
        this.getGatewayList(e.toString())
      } else {
        this.queryParam.gatewayIds = ''
        this.handleOk()
      }
    },
    getStationTree () {
      treeList(Object.assign(this.queryParam)).then(res => {
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.treeList = res.data
      })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getGatewayList (stationId) {
      gatewayList({ stationId: stationId }).then(res => {
        if (res.success) {
          this.gatewayList = res.data
          this.gatewayIds = []
          this.gatewayList.filter(value => {
            this.gatewayIds.push(value.id)
          })
          this.queryParam.gatewayIds = this.gatewayIds.toString()
          this.handleOk()
        }
      })
    },
    syncModel () {
      if (typeof (this.queryParam.gatewayId) === 'undefined') {
        this.$message.error('请选择需要同步模型的网关')
        return
      }
      sync({ gatewayId: this.queryParam.gatewayId })
        .then(res => {
          if (res.success) {
            this.$message.success('同步成功，采集端正在上报数据，请稍后刷新')
            this.$refs.table.refresh()
          } else {
            this.$message.error('同步失败' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('同步错误：' + err.message)
        })
    }
  }
}
</script>

<style lang="less" scoped>
@import '../../../assets/css/list.less';
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
  .table-page-search-wrapper{
    padding: 0 10px;
    /deep/ .ant-row{
      margin-left: 0px !important;
    }
  }
</style>
